package com.cloud.mall.test.service;

import cn.hutool.core.bean.BeanUtil;
import com.cloud.mall.dto.test.Order;
import com.cloud.mall.dto.test.Product;
import com.cloud.mall.result.GeneralResponse;
import com.cloud.mall.test.client.ProductServiceClient;
import com.cloud.mall.test.client.StorageServiceClient;
import com.cloud.mall.test.client.UserServiceClient;
import com.cloud.mall.test.entity.OrderTbl;
import com.cloud.mall.test.mapper.OrderTblMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: 梁二东
 * @Date: 2024/12/16 10:54
 * @Description:
 **/
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderTblMapper orderTblMapper;

    @Resource
    private UserServiceClient userServiceClient;
    @Resource
    private StorageServiceClient storageServiceClient;
    @Resource
    private ProductServiceClient productServiceClient;

    @Override
    @GlobalTransactional(name = "createOrder", rollbackFor = Exception.class)
    public Order create(String userId, String commodityCode, int orderCount) {
        // 计算订单金额
        int orderMoney = calculate(commodityCode, orderCount);
        // 扣除用户金额
        userServiceClient.debit(userId, orderMoney);

        OrderTbl order = new OrderTbl();
        order.setUserId(userId);
        order.setCommodityCode(commodityCode);
        order.setCount(orderCount);
        order.setMoney(orderMoney);
        // INSERT INTO orders ...
        orderTblMapper.insert(order);

        // deduct storage by commodityCode
        storageServiceClient.deduct(commodityCode, orderCount);
        return BeanUtil.toBean(order, Order.class);
    }

    @Override
    public Order getOrderById(Integer id) {
        return BeanUtil.toBean(orderTblMapper.selectById(id), Order.class);
    }

    private int calculate(String commodityCode, int orderCount) {
        GeneralResponse<Product> productCommonResult = productServiceClient.selectByCommodityCode(commodityCode);
        Product product = productCommonResult.getData();
        int orderMoney = product.getPrice() * orderCount;
        log.info("计算订单总金额orderMoney：【{}】", orderMoney);
        return orderMoney;
    }
}
